/*
* File: Allocator.h
*/
#ifndef ALLOCATOR_H
#define ALLOCATOR_H
#include <cstddef>
// 参考资料如下：
//	http://www.cplusplus.com/reference/std/memory/allocator/
//	泛型编程和stl 侯捷译 10.3 10.4
//	c++ primer 第四版 18.1.2allocator类


class BadAlloc {

};


template <class T>
class Allocator {
public:
	typedef	T		value_type;
	typedef	T*		pointer;
	typedef	T&		reference;
	typedef	const T*	const_pointer;
	typedef	const T&	const_reference;
	typedef	size_t		size_type;
	typedef	ptrdiff_t	difference_type;
	pointer address ( reference x ) const
	{
		return &x;
	}

	const_pointer address ( const_reference x ) const
	{
		return &x;
	}

	pointer allocate (size_type n)
	{
		pointer mem = (pointer)::operator new(n * sizeof(value_type));
		if (!mem)
			throw BadAlloc();
		
		return mem;
	}

	void construct ( pointer p, const_reference val )
	{
		new ((void *)p) T(val);
	}
	

	// 在这里假定分配的内存是连续的
	void deallocate (pointer p, size_type n)
	{
	//	destroy(p, p + n)
		::operator delete [] (p);
	}


	void destroy (pointer p)
	{
		((T*)p)->~T();
	}

	template<class ForwardIterator>
	void destroy(ForwardIterator first, ForwardIterator last)
	{
		for (; first != last; ++first)
			destroy(&*first);
	}

	size_type max_size() const throw()
	{
		return (-1) / sizeof(T);
	}

	// 先不考虑实现了commit和rollback属性
	// uninitialized_copy代码修改自泛型编程与stl 10.4内存管理
	template <class InputIterator, class ForwardIterator>
	ForwardIterator
	uninitialized_copy(InputIterator first, InputIterator last, 
			ForwardIterator result)
	{
		ForwardIterator cur = result;

		for (; first != last; ++first, ++cur)
			construct(&(*cur), *first);
			
		return cur;
	}

	template <class ForwardIterator >
	void uninitialized_fill(ForwardIterator first, ForwardIterator last,
		const T& x)
	{
		for (;first != last; ++first)
			construct(&*first, x);
	}
	
	template<class ForwardIterator>
	ForwardIterator
	uninitialized_fill_n(ForwardIterator first, size_type n,
				 const_reference x)
	{
		uninitialized_fill(first, first + n, x);
	}
	
};



#endif
